// pages/hotel_detail/hotel_detail.ts

interface Hotel {
  id: number;
  name: string;
  rating: number;
  reviewCount: number;
  tags: string[];
  brief: string;
  location: string;
  distance: string;
  lowestPrice: number;
  images: string[];
  description: string;
  wellness: Array<{
    icon: string;
    title: string;
    description: string;
    bgColor: string;
  }>;
  policies: Array<{
    name: string;
    value: string;
  }>;
  facilities: Array<{
    title: string;
    items: Array<{
      icon: string;
      name: string;
    }>;
  }>;
  rooms: Array<{
    id: number;
    name: string;
    image: string;
    tags: string[];
    features: Array<{
      icon: string;
      text: string;
    }>;
    price: number;
  }>;
  reviews: Array<{
    id: number;
    username: string;
    avatar: string;
    rating: number;
    time: string;
    content: string;
    images: string[];
    roomName: string;
  }>;
}

interface PageData {
  hotel: Hotel;
  tabValue: string;
  scrolled: boolean;
  isFavorite: boolean;
  reviewFilter: string;
  filteredReviews: Array<Hotel['reviews'][0]>;
  calendarVisible: boolean;
  checkInDate: string;
  checkOutDate: string;
  stayNights: number;
  checkInTimestamp: number;
  checkOutTimestamp: number;
  minDate: number;
  maxDate: number;
}

interface PageInstance {
  setInitialDates: () => void;
  filterReviews: () => void;
  getHotelDetail: (id: string) => void;
}

Page<PageData, PageInstance>({
  data: {
    hotel: {
      id: 1,
      name: '青岩古镇温泉客栈',
      rating: 4.9,
      reviewCount: 358,
      tags: ['私家温泉', '特色民宿', '苗族风情'],
      brief: '位于青岩古镇中心，明清古建筑风格，每间客房配有私家温泉池',
      location: '贵州省贵阳市花溪区青岩镇',
      distance: '距市中心15km',
      lowestPrice: 588,
      images: [
        'https://images.unsplash.com/photo-1566073771259-6a8506099945',
        'https://images.unsplash.com/photo-1520250497591-112f2f40a3f4',
        'https://images.unsplash.com/photo-1512918728675-ed5a9ecdebfd'
      ],
      // 酒店描述
      description: '青岩古镇温泉客栈坐落于有着400多年历史的青岩古镇中心，由多栋明清古建筑改造而成，完美保留了原有的古典建筑风格和特色。\n\n每间客房都配有私家温泉池，温泉水引自山脉深处，富含多种矿物质，有助于舒缓疲劳、改善睡眠和促进血液循环。\n\n酒店环境幽静，四周被青山环抱，空气清新，是休闲康养、避暑度假的理想选择。',
      
      // 康养特色
      wellness: [
        {
          icon: 'heart',
          title: '天然温泉',
          description: '温泉水引自深层岩石，富含硫磺、钙、镁等矿物质，具有舒缓肌肉、促进血液循环的功效',
          bgColor: 'bg-orange-red'
        },
        {
          icon: 'user',
          title: '中医养生',
          description: '提供传统中医诊脉、推拿、艾灸等养生服务，配合温泉浴，达到更好的养生效果',
          bgColor: 'bg-green-purple'
        },
        {
          icon: 'root-list',
          title: '特色药膳',
          description: '酒店餐厅提供苗族特色药膳，采用当地新鲜食材和中草药，营养丰富且有养生功效',
          bgColor: 'bg-blue-indigo'
        }
      ],
      
      // 酒店政策
      policies: [
        { name: '入住时间', value: '14:00后' },
        { name: '退房时间', value: '12:00前' },
        { name: '宠物', value: '不可携带宠物' },
        { name: '儿童政策', value: '12岁以下儿童可免费入住' },
        { name: '加床', value: '可加床，额外收费¥200/晚' },
        { name: '早餐', value: '中西式自助早餐，¥68/人' },
        { name: '付款方式', value: '支持微信、支付宝、银联' }
      ],
      
      // 设施服务
      facilities: [
        {
          title: '基础设施',
          items: [
            { icon: 'wifi', name: '免费WiFi' },
            { icon: 'air-conditioning', name: '空调' },
            { icon: 'shop', name: '餐厅' },
            { icon: 'parking', name: '停车场' },
            { icon: 'device', name: '电梯' },
            { icon: 'swap', name: '24小时前台' },
            { icon: 'luggage', name: '行李寄存' },
            { icon: 'secured', name: '保险箱' }
          ]
        },
        {
          title: '康养设施',
          items: [
            { icon: 'heart', name: '温泉' },
            { icon: 'user', name: '按摩室' },
            { icon: 'chart', name: '健身房' },
            { icon: 'image', name: '瑜伽室' },
            { icon: 'tree', name: '花园' },
            { icon: 'book-open', name: '阅读区' }
          ]
        },
        {
          title: '客房设施',
          items: [
            { icon: 'tv-1', name: '电视' },
            { icon: 'queue', name: '电热水壶' },
            { icon: 'home', name: '浴缸' },
            { icon: 'shower', name: '淋浴' },
            { icon: 'mirror', name: '吹风机' },
            { icon: 'shop', name: '迷你吧' },
            { icon: 'desktop', name: '书桌' },
            { icon: 'control-platform', name: '空调' }
          ]
        }
      ],
      
      // 房型信息
      rooms: [
        {
          id: 1,
          name: '苗族风情温泉大床房',
          image: 'https://images.unsplash.com/photo-1578683010236-d716f9a3f461',
          tags: ['大床', '私家温泉', '40平米'],
          features: [
            { icon: 'user', text: '可住2人' },
            { icon: 'wifi', text: '免费WiFi' },
            { icon: 'shop', text: '含早餐' },
            { icon: 'root-list', text: '大床1.8m×2m' }
          ],
          price: 688
        },
        {
          id: 2,
          name: '古镇景观温泉双床房',
          image: 'https://images.unsplash.com/photo-1590490360182-c33d57733427',
          tags: ['双床', '私家温泉', '45平米'],
          features: [
            { icon: 'user', text: '可住2人' },
            { icon: 'wifi', text: '免费WiFi' },
            { icon: 'shop', text: '含早餐' },
            { icon: 'root-list', text: '双床1.2m×2m' }
          ],
          price: 728
        },
        {
          id: 3,
          name: '江景温泉套房',
          image: 'https://images.unsplash.com/photo-1551105378-78e609e1d468',
          tags: ['套房', '江景', '私家温泉', '65平米'],
          features: [
            { icon: 'user', text: '可住3人' },
            { icon: 'wifi', text: '免费WiFi' },
            { icon: 'shop', text: '含早餐' },
            { icon: 'root-list', text: '1大床+1单人床' }
          ],
          price: 988
        }
      ],
      
      // 评价数据
      reviews: [
        {
          id: 1,
          username: '清风明月',
          avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde',
          rating: 5,
          time: '2023-09-20',
          content: '环境非常好，就在青岩古镇里面，随时可以出去逛逛。房间的私家温泉太赞了，晚上泡着温泉看星星，非常惬意。早餐种类丰富，中西式都有，服务人员态度很好。',
          images: [
            'https://images.unsplash.com/photo-1580977276076-ae4b8c219b8e',
            'https://images.unsplash.com/photo-1503043057261-e4b2c6c241c7'
          ],
          roomName: '苗族风情温泉大床房'
        },
        {
          id: 2,
          username: '温泉爱好者',
          avatar: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330',
          rating: 4,
          time: '2023-08-15',
          content: '作为温泉控，这家客栈的温泉水质真的很好，矿物质含量高，泡完后皮肤很滑。店家还会提供中草药包可以放在温泉里，很特别的体验。唯一缺点是停车不太方便。',
          images: [],
          roomName: '古镇景观温泉双床房'
        },
        {
          id: 3,
          username: '慢旅行',
          avatar: 'https://images.unsplash.com/photo-1599566150163-29194dcaad36',
          rating: 5,
          time: '2023-07-30',
          content: '带父母来养生度假，效果非常好！每天早上有免费的太极课程，温泉水温度可调，晚上还有苗族风情表演。住了三天，全家人都很放松，尤其是有慢性疲劳的妈妈，睡眠质量明显改善。',
          images: [
            'https://images.unsplash.com/photo-1572847329737-ac2f85b16041'
          ],
          roomName: '江景温泉套房'
        }
      ]
    },
    tabValue: 'rooms', // 当前选中的标签页
    scrolled: false, // 是否已滚动
    isFavorite: false, // 是否收藏
    reviewFilter: 'all', // 评价筛选：all-全部，positive-好评，latest-最新
    filteredReviews: [], // 筛选后的评价
    
    // 日期选择相关
    calendarVisible: false, // 日历弹窗是否显示
    checkInDate: '11月15日', // 入住日期
    checkOutDate: '11月17日', // 离店日期
    stayNights: 2, // 入住晚数
    checkInTimestamp: new Date().getTime(), // 入住时间戳
    checkOutTimestamp: new Date().getTime() + 2 * 24 * 60 * 60 * 1000, // 离店时间戳
    minDate: new Date().getTime(), // 最小可选日期（今天）
    maxDate: new Date().getTime() + 180 * 24 * 60 * 60 * 1000 // 最大可选日期（180天后）
  },

  onLoad: function (options: Record<string, string>) {
    // 获取酒店ID
    const id = options.id;
    if (id) {
      // 根据ID从服务器获取酒店详情
      // this.getHotelDetail(id);
    }
    
    // 初始化筛选后的评价列表
    this.setData({
      filteredReviews: this.data.hotel.reviews
    });
    
    // 设置初始日期
    this.setInitialDates();
  },

  onReady: function () {
    // 监听页面滚动
    wx.createIntersectionObserver().relativeToViewport().observe('.gallery-container', (res) => {
      if (res.intersectionRatio < 0.5) {
        this.setData({ scrolled: true });
      } else {
        this.setData({ scrolled: false });
      }
    });
  },

  // 设置初始日期
  setInitialDates: function() {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dayAfterTomorrow = new Date(today);
    dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);
    
    const formatDate = (date: Date): string => {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    };
    
    this.setData({
      checkInDate: formatDate(tomorrow),
      checkOutDate: formatDate(dayAfterTomorrow),
      checkInTimestamp: tomorrow.getTime(),
      checkOutTimestamp: dayAfterTomorrow.getTime(),
      stayNights: 1
    });
  },

  // Tab切换
  onTabChange: function (e: any) {
    this.setData({
      tabValue: e.detail.value
    });
  },

  // 返回上一页
  navigateBack: function () {
    wx.navigateBack();
  },

  // 分享
  handleShare: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 收藏
  handleFavorite: function () {
    this.setData({
      isFavorite: !this.data.isFavorite
    });
    
    wx.showToast({
      title: this.data.isFavorite ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 预览图片
  previewImage: function (e: any) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.hotel.images[index],
      urls: this.data.hotel.images
    });
  },

  // 预览房型图片
  previewRoomImage: function (e: any) {
    const roomId = e.currentTarget.dataset.roomId;
    const room = this.data.hotel.rooms.find(r => r.id === roomId);
    
    if (room) {
      wx.previewImage({
        current: room.image,
        urls: [room.image]
      });
    }
  },

  // 打开地图位置
  openLocation: function () {
    // 这里应该有实际的经纬度数据
    // 示例数据
    wx.openLocation({
      latitude: 26.5837,
      longitude: 106.6992,
      name: this.data.hotel.name,
      address: this.data.hotel.location
    });
  },

  // 筛选评价
  setReviewFilter: function (e: any) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      reviewFilter: filter
    });
    this.filterReviews();
  },

  // 处理评价筛选
  filterReviews: function (): void {
    let reviews = this.data.hotel.reviews;
    let filtered: Array<Hotel['reviews'][0]> = [];
    
    switch (this.data.reviewFilter) {
      case 'positive':
        filtered = reviews.filter(review => review.rating >= 4);
        break;
      case 'latest':
        filtered = [...reviews].sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
        break;
      default:
        filtered = reviews;
    }
    
    this.setData({
      filteredReviews: filtered
    });
  },

  // 预览评价图片
  previewReviewImage: function (e: any) {
    const reviewIndex = e.currentTarget.dataset.reviewIndex;
    const imgIndex = e.currentTarget.dataset.imgIndex;
    const review = this.data.hotel.reviews[reviewIndex];
    
    wx.previewImage({
      current: review.images[imgIndex],
      urls: review.images
    });
  },

  // 显示日历选择
  showCalendar: function () {
    this.setData({
      calendarVisible: true
    });
  },

  // 隐藏日历选择
  hideCalendar: function () {
    this.setData({
      calendarVisible: false
    });
  },

  // 日历弹窗状态变化
  onCalendarVisibleChange: function (e: any) {
    if (!e.detail.visible) {
      this.hideCalendar();
    }
  },

  // 日历选择确认
  onCalendarConfirm: function (e: any) {
    const { start, end } = e.detail.value;
    
    // 计算入住晚数
    const startDate = new Date(start);
    const endDate = new Date(end);
    const nights = Math.floor((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
    
    // 格式化日期显示
    const formatDate = (timestamp: number): string => {
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    };
    
    this.setData({
      checkInTimestamp: start,
      checkOutTimestamp: end,
      checkInDate: formatDate(start),
      checkOutDate: formatDate(end),
      stayNights: nights,
      calendarVisible: false
    });
  },

  // 查看所有房型
  showAllRooms: function () {
    this.setData({
      tabValue: 'rooms'
    });
  },

  // 预订房间
  bookRoom: function (e: any) {
    const roomId = e.currentTarget.dataset.roomId;
    const room = this.data.hotel.rooms.find(r => r.id === roomId);
    
    if (room) {
      wx.navigateTo({
        url: `/pages/order_detail/order_detail?id=${this.data.hotel.id}&room_id=${roomId}&type=hotel&check_in=${this.data.checkInTimestamp}&check_out=${this.data.checkOutTimestamp}`
      });
    }
  },

  // 获取酒店详情
  getHotelDetail: function (id: string): void {
    wx.showLoading({
      title: '加载中',
    });
    
    // 这里应该是从服务器获取数据
    // 模拟API请求
    setTimeout(() => {
      // 如果是真实环境，这里会用实际接口返回的数据更新this.data.hotel
      
      // 获取完数据后，初始化筛选后的评价列表
      this.setData({
        filteredReviews: this.data.hotel.reviews
      });
      
      wx.hideLoading();
    }, 500);
  },

  onShareAppMessage: function () {
    return {
      title: `【贵州四季康养】${this.data.hotel.name} - ${this.data.hotel.tags[0]}`,
      path: `/pages/hotel_detail/hotel_detail?id=${this.data.hotel.id}`,
      imageUrl: this.data.hotel.images[0]
    };
  }
}) 